<?php 
   
   /**
    * The class youtube api to get content from Youtube
    *@since 26/12/2013
    *@author ChinhTB  
   */
   
   class YoutubeApi{
      /**
       * 
       * The constructor
      */
      public function __construct(){}
      
      /**
       * 
       * Function get info video from Link
       * @access public
       * @param $url string
       * @return array info video
      */
      public static function getInfoMovie($url){
         $id_movie = self::getYouTubeIdFromURL($url);
         $link_api = "https://gdata.youtube.com/feeds/api/videos/".$id_movie."?v=2&alt=json";
         $code     = self::get_http_response_code($link_api);
         $array_info = array('code' => $code,'message' => 'Link không tồn tại');
         if($code == 200){
            $respone_youtube = json_decode(file_get_contents($link_api),true);
            $entry = $respone_youtube['entry'];
            $title = $entry['title']['$t'];
            $view  = $entry['yt$statistics']['viewCount'];
            $description = $entry['media$group']['media$description']['$t'];
            $duration = $entry['media$group']['yt$duration']['seconds'];
            $array_info = array( 'code' => $code,
                                 'message' => 'Success', 
                                 'data' => array('id' => $id_movie,
                                                 'name' => $title,
                                                 'view' => $view,
                                                 'duration' => $duration,
                                                 'description' => $description)
                               );   
         }
         return $array_info;
      }
      
      /**
       * 
       * Get list movie from Playlist
       * @param $url string
       * @return array movie
      */
      public static function getMovieFromPlayList($url){
         $id_playlist = self::detectedIdPlaylist($url);
         //$link_api = "http://gdata.youtube.com/feeds/api/playlists/".$id_playlist."?max-results=25&start-index=1&alt=json";
         $link_api = "http://gdata.youtube.com/feeds/api/playlists/".$id_playlist."?alt=json";
         $code     = self::get_http_response_code($link_api);         
         $array_return = array('code' => $code,'message' => 'Link không tồn tại' , 'link_api' => $link_api );
         if($code == 200){
            $respone_youtube = json_decode(file_get_contents($link_api),true);
            $totalMovie = $respone_youtube['feed']['openSearch$totalResults']['$t'];
            if($totalMovie >  0){
               $i = 1;
               $max_results = 20;
               while($i <= $totalMovie){
                  $start_index = $i;
                  $i += $max_results;
                  $link_api = "http://gdata.youtube.com/feeds/api/playlists/".$id_playlist."?max-results=".$max_results."&start-index=".$start_index."&alt=json";
                  $respone_youtube = json_decode(file_get_contents($link_api),true);
                  $entry = isset($respone_youtube['feed']['entry']) ? $respone_youtube['feed']['entry'] : array();
                  if(count($entry) > 0){
                     $array_info[] = $entry;
                     $array_return = array('code' => $code,'message' => 'Success');
                     foreach($array_info as $info){
                        foreach($info as $value){
                           if(isset($value['media$group']['media$thumbnail'][0]['url'])){
                              $id_movie = self::detectedIdMoive($value['media$group']['media$thumbnail'][0]['url']);   
                           }
                           $sate = isset($value['app$control']['yt$state']['reasonCode']) ? $value['app$control']['yt$state']['reasonCode'] : 'public';
                           // Check video is Private or Deleted
                           if($sate != 'suspended' && $sate != 'private'){
                              $array_return['data'][] = array( 'id' => $id_movie,
                                                               'sate' => $sate,
                                                               'name' => $value['title']['$t'],
                                                               'duration' => isset($value['media$group']['media$content'][0]['duration']) ? $value['media$group']['media$content'][0]['duration'] : rand(300,500),
                                                               'view' => isset($value['yt$statistics']['viewCount']) ? $value['yt$statistics']['viewCount'] : rand(10000,50000)
                                                               //,'description' =>$value['content']['$t']
                                                             );
                           }
                           
                        }
                     }   
                  }
                  
               }
            }
              
         }
         return $array_return;
      }
      
      /**
       * 
       * Get list video from API search
       * @param strin keyword
       * @return array video
      */
      public static function searchMovie($keyword,$start_index = 1,$max_results = 20){
         $array_return = array();
         $data         = array();
         $message      = 'Missed';
         $code         = 0;
         if(trim($keyword) != ""){
            $keyword  = urlencode($keyword);
            $link_api = "https://gdata.youtube.com/feeds/api/videos?q=".$keyword."&start-index=".$start_index."&max-results=".$max_results."&alt=json";
            $code     = self::get_http_response_code($link_api);
            if($code == 200){
               $respone_youtube = json_decode(file_get_contents($link_api),true);
               $entry = isset($respone_youtube['feed']['entry']) ? $respone_youtube['feed']['entry'] : false;
               if($entry){
                  $message = 'Success';
                  //echoArray($entry);
                  foreach($entry as $value){
                     $id         = self::getYouTubeIdFromURL($value['link'][0]['href']);
                     $title      = $value['title']['$t'];   
                     $duration   = $value['media$group']['yt$duration']['seconds'];
                     $view       = $value['yt$statistics']['viewCount'];
                     $data[] = array('id' => $id,  
                                     'name' => $title,
                                     'view' => $view,
                                     'duration' => $duration
                                    );
                  }
               }
            } 
         }
         $array_return = array('code' => $code,'message' => $message, "data" => $data);  
         return $array_return;
      }
      
      /**
       * 
       * Function detect id from Link
       * @access private
       * @param $link string
       * @return string ID movie
      */
      private static function detectedIdMoive($link){
         $id = '';
         if($link != ''){
            $indexOfW = strpos($link,'watch?v=');
            if($indexOfW){
               $id = substr($link,$indexOfW+8);
            }
            else{
               $arr = explode('/',$link);
               array_pop($arr);
               $id = end($arr);
            }
         }
         return $id;
      }
      
      
      
      /**
       * 
       * Function detect id from link
       * @access private
       * @param $link string
       * @return string ID movie
      */
      private static function getYouTubeIdFromURL($url){
         $video_id = 'NULL';
         if (preg_match('%(?:youtube\.com/(?:user/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i', $url, $result)) {
            $video_id = $result[1];
         }
         return $video_id;
      }
         
      
      
      
      
      
      
      /**
       * 
       * Function detect id from Link
       * @access private
       * @param $link string
       * @return string ID movie
      */
      private static function detectedIdPlaylist($link){
         $id = '';
         if($link != ''){
            $indexOfW = strpos($link,'list=');
            $id = substr($link,$indexOfW+5);
         }
         return $id;
      }
      
      /**
       * 
       * Detect link Youtube is singer video or playlist
       * @param $url link
       * @return int 0 unknow 1 is singer video 2 is playlist 
      */
      public static function detectUrl($url){
         $check = 0;
         if($url != ''){
            if(strpos($url,'&list='))
               $check = 2;
            else{
               if(strpos($url,'watch?v'))
                  $check = 1;
            }
         }
         return $check;
      }
      
      
      /**
       * 
       * Get respone code header url
      */
      public static function get_http_response_code($url) {
        $headers = get_headers($url);
        return substr($headers[0], 9, 3);
      }
   }
?>